import { resolve, isAbsolute } from 'path'
import { isArray, isSymbol, isDef, isNil, validateURL as isExternalLink } from '@guanwei/app-javascript'
import { assert, warn } from '@/utils/logger'

import BasicLayout from '@/layouts/BasicLayout'
import BlankLayout from '@/layouts/BlankLayout'

/**
 * 格式化路由，主要配合组件 `src/components/GlobalSider/SiderMenu.jsx` 使用
 * @param routes 传入的原始路由，详情见 `src/router/index.js` 注释描述
 * @param rootpath 根级目录
 */
export function formatSiderMenuRoutes(routes, rootpath) {
  if (!isArray(routes)) return []

  const _iterator = (data = [], basepath = '') => {
    // return data.filter(r => !r.hidden).reduce((previousRoutes, r) => {
    return data.reduce((previousRoutes, r) => {
      let currentPath = r.path

      if (!isExternalLink(r.path) && !isAbsolute(r.path)) {
        currentPath = resolve(basepath, r.path)
      }

      if (r.alwaysShow) {
        // 检测是否提供了 meta.title 配置，如果无给出警告并采用默认配置
        if (isNil(r.meta)) {
          warn('使用 alwaysShow 属性需要提供 meta 配置')
          r.meta = {}
          r.meta.title = isSymbol(r.name) ? r.name.toString() : r.name
        }

        assert(isNil(r.component), '使用 alwaysShow 属性必须提供 component 属性')
      }

      if (r.redirect && isArray(r.children) && r.children.filter(r => !r.hidden).length === 1 && !r.alwaysShow) {
        // 当存在 redirect，仅仅包含一个非隐藏子路由且非总展现，提升子路由一级
        previousRoutes.push(...formatSiderMenuRoutes(r.children, currentPath))
      } else {
        if (r.meta && isDef(r.path)) {
          previousRoutes.push({
            ...r,
            path: currentPath,
            children: isArray(r.children) && r.children.length ? _iterator(r.children, currentPath) : []
          })
        }
      }

      return previousRoutes
    }, [])
  }

  return _iterator(routes, rootpath)
}

export function formatServerRoutes(routes) {
  const accessedRoutes = []

  if (!isArray(routes)) { return accessedRoutes }

  routes.forEach(r => {
    let children = []
    let component = r.component
    let componentVNode

    if (component) {
      if (component.slice(0, 1) === '/') {
        component = component.slice(1)
      }
      if (component === 'BasicLayout') {
        componentVNode = BasicLayout
      } else if (component === 'BlankLayout') {
        componentVNode = BlankLayout
      } else {
        // 注意此处会扫描全局的文件，所以临时注释，如果需要请放开注释
        // 所有你需要配置一个完整且没有错误的项目
        // 还有移除注释 /* webpackIgnore: true */，不然打包会出现问题
        // componentVNode = process.env.NODE_ENV === 'production'
        //   ? () => import(/* webpackIgnore: true */'@/views/' + component)
        //   : require(/* webpackIgnore: true */'@/views/' + component).default
      }
    }

    if (r.children && r.children.length) {
      children = formatServerRoutes(r.children)
    }

    accessedRoutes.push({ ...r, component: componentVNode, children })
  })

  return accessedRoutes
}
